package com.example.eurekac.controller;

import com.alibaba.fastjson.JSON;
import com.example.eurekac.entity.*;
import com.example.eurekac.service.UserService;
import com.example.eurekac.utils.JwtHelper;
import com.example.eurekac.utils.RedisUtil;
import com.sun.org.apache.xerces.internal.dom.PSVIAttrNSImpl;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

@RefreshScope
@RestController
@RequestMapping(value = "/test")
public class TestController {
    // 请求总数
    public static int clientTotal = 5000;

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    public static int count = 0;
    private static Logger logger= LoggerFactory.getLogger(TestController.class);
    @Autowired
    private Audience audience;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    UserService userService;
    @Value("${audience.base64Secret}")
    private String word;
    @Value("${foo}")
    private String foo;
    @Value("${neo.hello}")
    private String ve;
    @GetMapping("/hi")
    public String test(HttpServletRequest request) {
        System.out.println("1:"+request.getContextPath());
        System.out.println("2:"+request.getServletPath());
        System.out.println("3:"+request.getRequestURI());
        System.out.println("4:"+request.getRealPath("/"));
        String token = login("123456", "1", request);
        Claims c = JwtHelper.parseJWT(token, word);
        String data = c.getId() + c.get("role") + c.get("unique_name") + c.get("userid");
        return data;
    }

    @GetMapping("/hiyt")
    public String redistest(String name,String password) {
        System.out.println("name："+name+"================="+"password:"+password);
       // User user=new User();
       // String a=user.getPassword().toString();
        Long time=Long.valueOf("60");
        if (redisUtil.set("gg", "ttt")) {
            redisUtil.set("tt","123",time);
            logger.info("成功");
            return "成功"+redisUtil.get("tt");
        } else {
            logger.info("失败");
            return "失败";
        }
    }

    @GetMapping("/git")
    public String git() {
        return redisUtil.get("tt");
    }

    @GetMapping("/token")
    public String gettoken(@RequestParam(value = "password") String password) {

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String pass = encoder.encode(password);
        StringBuilder sb = new StringBuilder();
        sb.append("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat(sb.toString());
        String dateString = sdf.format(new Date());

        User user = new User();
        user.setCreateDate(dateString);
        user.setEmail("sddddddsdf");
        user.setId(Long.valueOf("1"));
        user.setPassword(pass);
        user.setRole("测试");
        user.setUsername("测试");
        userService.insertPassWord(user);
        return "成功";
    }

    //登录获取token
    @GetMapping(value = "/login")
    public String login(@RequestParam(value = "password") String password, @RequestParam(value = "id") String id, HttpServletRequest request) {
        //User user = new User();
/*        Boolean is_email = MatcherUtil.matcherEmail(usernameOrEmail);
        User user = new User();
        if (is_email) {
            user.setEmail(usernameOrEmail);
        } else {
            user.setUsername(usernameOrEmail);
        }
        User query_user = userService.get(user);
        if (query_user == null) {
            return "400, 用户名或邮箱错误";
        }*/
        User query_user = userService.selectByPrimaryKey(id);
        //验证密码
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean is_password = encoder.matches(password, query_user.getPassword());
        if (!is_password) {
            //密码错误，返回提示
            return "400, 密码错误";
        }

        String jwtToken = JwtHelper.createJWT(query_user.getUsername(),
                query_user.getId().toString(),
                query_user.getRole(),
                audience.getClientId(),
                audience.getName(),
                audience.getExpiresSecond() * 1000,
                audience.getBase64Secret());

        String result_str = jwtToken;
        return result_str;
    }

    @GetMapping(value = "/gbf")
    public String gaobf(){
        ExecutorService executorService = Executors.newCachedThreadPool();
        //信号量，此处用于控制并发的线程数
        final Semaphore semaphore = new Semaphore(threadTotal);
        //闭锁，可实现计数器递减
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal ; i++) {
            executorService.execute(() -> {
                try {
                    //执行此方法用于获取执行许可，当总计未释放的许可数不超过200时，
                    //允许通行，否则线程阻塞等待，直到获取到许可。
                    semaphore.acquire();
                    add();
                    System.out.println(new Date()+"=================================="+userService.id());
                    //释放许可
                    semaphore.release();
                } catch (Exception e) {
                    //log.error("exception", e);
                    e.printStackTrace();
                }
                //闭锁减一
                countDownLatch.countDown();
            });
        }
       // countDownLatch.await(2000,TimeUnit.NANOSECONDS);//线程阻塞，直到闭锁值为0时，阻塞才释放，继续往下执行
        executorService.shutdown();
        logger.info("count:{}", count);
        System.out.println(new Date()+"=================================="+count);
         return String.valueOf(count);
    }

    private static void add() {
        count++;
    }
    //jsp页面访问ztree数据
    @RequestMapping("/name")
    public ModelAndView name(Map<String, Object> map,HttpServletRequest request){
        ModelAndView mv=new ModelAndView();
        City city=new City();
        city.setPid(0);
        List<City> data=this.userService.getCity(city);
        List<TreeNode> list=new ArrayList<>();
        Map<Integer,String> mapPid=new HashMap<>();
        //存入父级名称和id
        for (int i=0;i<data.size();i++){
            TreeNode node=new TreeNode();
            List<TreeNode> d=DG(data.get(i).getId());
            node.setCityId(data.get(i).getId());
            node.setName(data.get(i).getName());
            node.setChildren(d);
            list.add(node);
        }
        String json=JSON.toJSONString(list);
        //获取当前页数
        int pagenum=request.getParameter("pageNum")==null?1:Integer.valueOf(request.getParameter("pageNum"));
        PageBean pb=getPage(pagenum);
        mv.addObject("pageBean",pb);
        map.put("name", "Clark");
        mv.addObject("name","周国峰");
        mv.addObject("nodes",json);
        mv.setViewName("hello");
        System.out.println("============================================");
        return mv;
    }

    /**
     * 递归组织ztree数据
     * @param id
     * @return
     */
    public List<TreeNode> DG(int id){
        List<TreeNode> listdata=new ArrayList<>();
        City city=new City();
        city.setPid(id);
        List<City> list=this.userService.getCity(city);
        if(list.size()>0){
            for (int i=0;i<list.size();i++){
                TreeNode node=new TreeNode();
                node.setCityId(list.get(i).getId());
                node.setName(list.get(i).getName());
                node.setChildren(DG(list.get(i).getId()));
                listdata.add(node);
            }
        }
        return  listdata;
    }

    /**
     * 分页
     * @param pagenum 获取当前页数
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public PageBean getPage(int pagenum){
        //每页显示多少条数据
        int pageSize=10;
        PageBean p=new PageBean();
        p.setPageSize(pageSize);
        p.setPageNum(pagenum);
        PageBean pb=userService.findUserMsgwithPage(p);
        return pb;
    }

    /**
     * 登录页面
     * @param model
     * @param response
     * @return
     */
    @RequestMapping(value = "/")
    public ModelAndView index(Model model, HttpServletResponse response) {
        model.addAttribute("name", "simonsfan");
        ModelAndView mv=new ModelAndView();
        mv.setViewName("index");
        return mv;
    }


    @Configuration
    public class DefaultView extends WebMvcConfigurerAdapter {
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("index");
            registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
            super.addViewControllers(registry);
        }
    }

}
